﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace AutoRoot
{
   public class TouchInput : MonoBehaviour, ILayerMaskUpdateListener
   {
      public LayerMask layer;

      private ILayerMaskController layerMaskController;

      private TouchedObjHandler touchedObjHandler;
      private TouchedPositionHandler touchedPositionHandler;

      void Start()
      {
         layerMaskController = Global.layerPlayer;
         GameObject Camera = GameObject.Find("Camera");
         Initialization init = Camera.GetComponent<Initialization>();
         touchedObjHandler = init.TouchedObjHandler;
         touchedPositionHandler = init.TouchedPositionHandler;
      }

      public void Update()
      {
#if UNITY_STANDALONE
         if (Input.GetMouseButton(0) || Input.GetMouseButtonDown(0) || Input.GetMouseButtonUp(0))
         {
            touchedPositionHandler.handleClickEvent(Input.mousePosition);
            Ray ray = camera.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerMaskController.GetLayerMask()))
            {
               GameObject obj = hit.transform.gameObject;
               touchedObjHandler.handleClickEvent(obj, hit.point);
            }
         }
#else
         if (Input.touchCount > 0)
         {
            foreach (Touch touch in Input.touches)
            {
               touchedPositionHandler.handleTouchEvent(touch);
               Ray ray = camera.ScreenPointToRay(touch.position);
               RaycastHit hit;
               if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerMaskController.GetLayerMask()))
               {
                  GameObject obj = hit.transform.gameObject;
                  touchedObjHandler.handleTouchEvent(obj, hit.point, touch);
               }
            }
         }
#endif
      }

      public void OnPalyerMode()
      {
         layerMaskController = Global.layerPlayer;
      }

      public void OnDropdownMenuMode()
      {
         layerMaskController = Global.layerDropdownMenu;
      }
   }
}